package image

import (
	"image"
	"image/color"
	"image/png"

	"github.com/afocus/captcha"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"github.com/nfnt/resize"
)

type imageConvertor int

var ImageConvertor imageConvertor = 1

func (i imageConvertor) Resize(img image.Image, width, height uint) image.Image {
	return resize.Resize(width, height, img, resize.MitchellNetravali)
}

func (i imageConvertor) Thumbnail(img image.Image, maxWidth, maxHeight uint) image.Image {
	return resize.Thumbnail(maxWidth, maxHeight, img, resize.MitchellNetravali)
}

type Verifier struct {
	cap *captcha.Captcha
}

func NewVerifier(font []byte) *Verifier {

	cap := captcha.New()
	err := cap.AddFontFromBytes(font)

	if err != nil {
		panic(err)
	}

	cap.SetSize(128, 64)
	cap.SetDisturbance(captcha.MEDIUM)
	cap.SetFrontColor(color.RGBA{255, 255, 255, 255})
	cap.SetBkgColor(color.RGBA{244, 80, 120, 12})

	return &Verifier{cap: cap}
}

func (v Verifier) GINHandler(ctx *gin.Context) {

	img, str := v.cap.Create(4, captcha.UPPER)
	ctx.Header("Content-Type", "image/png")

	s := sessions.Default(ctx)
	s.Set("v", str)
	s.Save()

	png.Encode(ctx.Writer, img)
}
